using Mono.Cecil;
using Mono.Cecil.Cil;

namespace Cil.Ast;

public class CreateObjectExpression : MethodCallExpression
{
	public CreateObjectExpression(Context context, Instruction position, MethodReference ctorMethod, params Expression[] exp_methodParams)
		: base(context, position, ctorMethod, new Expression(context), exp_methodParams)
	{
		if (ctorMethod.Name != ".ctor")
		{
			throw new ArgumentException("ctorMethod should be an object constructor");
		}

		IsConstructor = true;
		ReturnType = ctorMethod.DeclaringType;
	}

	public override string ToString()
	{
		return 
			ReturnType.IsArray 
				? string.Format("new {0}[{1}]", MethodReference.DeclaringType.GetElementType(), string.Join(", ", Parameters))
				: string.Format("new {0}({1})", MethodReference.DeclaringType, string.Join(", ", Parameters));
	}
}

public static partial class IlAst
{
	public static CreateObjectExpression CreateObject(Context context, Instruction position, MethodReference ctorMethod, params Expression[] exp_methodParams)
	{
		return new CreateObjectExpression(context, position, ctorMethod, exp_methodParams);
	}
}